/**
 * author:Administrator
 * date:2016/1/4
 * desc:TODO
 */

'use strict';

var Model = require('../model/couponVendor.js');
var counter = require('./counter.js');
var myCounter = counter.bindCounter(counter.TypesEnum.couponVendor);

var dao = {};

module.exports = dao;

dao.empty = function* () {
  return yield Model.remove({});
};

dao.add = function* (qtyTotal, qtyLeft) {
  var cvid = yield myCounter();
  var entity = new Model({
    cvid: cvid,
    qtyTotal: qtyTotal,
    qtyLeft: qtyLeft
  });
  return yield entity.save();
};

/**
 * @param cvid
 */
dao.getByCvid = function* (cvid) {
  return yield Model.findOne({
    cvid: cvid
  });
};

dao.transPhase_pending = function*(cvid, qty, tid) {
  return yield Model.findOneAndUpdate(
    {cvid: cvid, qtyLeft: {$gte: qty}, pendingTransactions: {$ne: tid}},
    {$inc: {qtyLeft: -qty}, $push: {pendingTransactions: tid}},
    {upsert: false, 'new': true}
  );
};

dao.transPhase_applied = function*(cvid, tid) {
  return yield Model.findOneAndUpdate(
    {cvid: cvid, pendingTransactions: {$all: tid}},
    {$pull: {pendingTransactions: tid}},
    {upsert: false, 'new': true}
  );
};

dao.findOneAndUpdate = function*(query, update, option) {
  return yield Model.findOneAndUpdate(query, update, option);
};

